﻿using Angle.Krill.Utils;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace Angle.Krill.SystemConfig
{
    internal class SysConfigHelper
    {
        private readonly string sysConfigPath = Path.Combine(Application.StartupPath, "tmp/sys.config.json");
        private readonly static object obj = new object();
        private volatile static SysConfigHelper instance;

        private SysConfig sysConfig;
        private SysConfigHelper() { }
        /// <summary>
        /// 缓存
        /// </summary>
        public static SysConfigHelper Instance
        {
            get
            {
                if (null == instance)
                {
                    lock (obj)
                    {
                        instance = new SysConfigHelper();
                    }
                }

                return instance;
            }
        }


        public SysConfig SysConfig
        {
            get
            {
                if (null == this.sysConfig)
                {
                    this.LoadSysConfig();
                }

                return this.sysConfig;
            }
        }

        public void LoadSysConfig()
        {
            try
            {
                if (File.Exists(this.sysConfigPath))
                {
                    this.sysConfig = JsonConvert.DeserializeObject<SysConfig>(File.ReadAllText(this.sysConfigPath));
                }

                if (null == this.sysConfig)
                {
                    this.sysConfig = new SysConfig();
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"加载全局配置错误", ex);
            }
        }
        public void SaveSysConfig(Action action = null)
        {
            action?.Invoke();

            File.WriteAllText(this.sysConfigPath, JsonConvert.SerializeObject(this.sysConfig));
        }
    }
}
